<template>
  <view class="container">
    <view class="step-wrap">
      <ve-steps :list="stepList" :active="activeStepListIndex" />
    </view>
    <view class="order-change-content" :style="{ 'padding-bottom': activeStepListIndex == 2 ? '250rpx' : '130rpx' }">
      <summary-info title="租赁信息" :summaryList="summaryLease" :defaultFold="false">
        <template #leasePeriod>
          <view class="lease-period">
            <view class="lease-period-val">{{ orderInfo.startTime ? `${orderInfo.startTime} - ${orderInfo.endTime}` : '-' }}</view>
            <view class="lease-period-rentdays" v-if="orderInfo.rentDays">租期：{{ orderInfo.rentDays }}</view>
          </view>
        </template>
      </summary-info>
      <!-- step1 -->
      <ve-form :model="form" layout="vertical" :rules="rules" ref="formRef">
        <ve-card class="relet-info" title="换下车信息" v-show="activeStepListIndex == 0">
          <box-info :carId="orderInfo.carId"></box-info>

          <ve-form-item required prop="replaceStaffId" label="换车人">
            {{ form.replaceStaffName }}
          </ve-form-item>
          <ve-form-item required prop="replaceTime" label="换车时间">
            <ve-date-picker v-model="form.replaceTime" :minDate="lastOrderCarInfo.useStartTime" mode="datetime" />
          </ve-form-item>
          <ve-form-item label="出库里程" unit="公里">
            {{ outCarMileage || 0 }}
          </ve-form-item>
          <ve-form-item label="出库油(电)量">
            {{ outCarOil || 0 }}
          </ve-form-item>
          <ve-form-item label="换下车里程" unit="公里" required prop="endCarMileage">
            <ve-input-number :precision="0" :min="lastOrderCarInfo.startCarMileage" v-model="form.endCarMileage" />
          </ve-form-item>
          <ve-form-item label="换下车油(电)量" required prop="endCarOil">
            <ve-input-number :precision="0" :min="1" :max="99999" v-model="form.endCarOil" />
          </ve-form-item>
          <ve-form-item label="换下车照片" labelPosition="top">
            <ve-upload v-model="form.returnFileIds" />
          </ve-form-item>
          <ve-form-item label="换下车视频" labelPosition="top" :borderBottom="false">
            <ve-upload-video v-model="form.returnVideoFileIds" :readonly="false" />
          </ve-form-item>
        </ve-card>
        <!-- step2 -->
        <ve-card title="换上车信息" :showDivider="false" v-show="activeStepListIndex == 1">
          <!-- <view class="platoon-wrapper">
            <platoon mode="changeCar" :customStyle="{ marginBottom: 0 }" />
          </view> -->
          <box-info :carId="form.carId"></box-info>

          <ve-form-item label="车辆来源">
            {{ form.carSource == 1 ? '门店车辆' : '跨门店调车' }}
          </ve-form-item>
          <ve-form-item label="车牌号">
            {{ form.carLicenseNo }}
          </ve-form-item>
          <ve-form-item label="车型">
            {{ form.carModelName }}
          </ve-form-item>
          <ve-form-item label="换上车里程" unit="公里" required prop="startCarMileage">
            <ve-input-number :precision="0" v-model="form.startCarMileage" />
          </ve-form-item>
          <ve-form-item label="换上车油(电)量" required prop="startCarOil">
            <ve-input-number :precision="0" :min="1" :max="99999" v-model="form.startCarOil" />
          </ve-form-item>
          <ve-form-item label="换上车照片" labelPosition="top">
            <ve-upload v-model="form.giveFileIds" />
          </ve-form-item>
          <ve-form-item label="换上车视频" labelPosition="top">
            <ve-upload-video v-model="form.giveVideoFileIds" :readonly="false" />
          </ve-form-item>
          <ve-form-item label="换车备注" labelPosition="top" :borderBottom="false">
            <ve-input type="textarea" v-model="form.replaceRemark" :maxlength="100" placeholder="请输入备注" />
          </ve-form-item>
        </ve-card>
      </ve-form>
      <!-- step3 -->
      <view class="fee-pane-content" v-show="activeStepListIndex == 2">
        <ve-form :model="feeForm" ref="feeFormRef" layout="vertical">
          <ve-card title="换车费用" fold>
            <template v-for="(item, index) in feeForm.orderFee" :key="index">
              <fee-pane :orderFeeIndex="index" :inlineCard="true" :disabledOnlineFee="orderInfo.orderSource == 1" />
            </template>
          </ve-card>
        </ve-form>
      </view>
    </view>
    <!-- footer -->
    <footer-box id="footer-box">
      <block v-if="activeStepListIndex == 0">
        <ve-button size="long" type="primary" @click="stepClickFn('next')">下一步 去完善换上车信息</ve-button>
      </block>
      <block v-if="activeStepListIndex == 1">
        <ve-button type="plain" @click="stepClickFn('prev')">上一步</ve-button>
        <ve-button type="primary" @click="stepClickFn('next')">下一步 去完善费用信息</ve-button>
      </block>
      <template #extra v-if="activeStepListIndex == 2">
        <feeStatistic />
      </template>
      <block v-if="activeStepListIndex == 2">
        <ve-button type="plain" @click="stepClickFn('prev')">上一步</ve-button>
        <ve-button type="primary" :loading="okLoading" @click="submitFn">完成</ve-button>
      </block>
    </footer-box>
  </view>
  <!-- 查询当前订单的换下车辆是否存在与当前订单关联的状态为已开始的ETC订单 -->
  <finishEtcOrderModal ref="etcModalRef" @ok="submitOperateFn" />
</template>
<script setup>
  import { ref, provide, computed } from 'vue'
  import { getShortOrdrDetailsAPI, checkExistEtcOrderApi } from '@/api/order/sOrder'
  import { finishReplaceCarAPI } from '@/api/order/workOrder'
  import finishEtcOrderModal from '../../../../order/components/finish-etc-order-modal.vue'
  import summaryInfo from './components/summary-info.vue'
  import boxInfo from './components/box-info.vue'
  import feePane from './components/order-fee/fee-pane.vue'
  import footerBox from './form/components/footerBox.vue'
  import feeStatistic from './components/order-fee/fee-statistic.vue'
  import { usePageDict } from '@/hooks/useDict'
  import { buildCostInfoParam, initFeeDetail, getStoreTemplateDetail } from './components/order-fee/fee-utils.js'
  import useFormFold from '@/hooks/useFormFold'
  import dayjs from 'dayjs'
  import { onLoad } from '@dcloudio/uni-app'
  import { getUserInfo } from './tools'
  import platoon from './form/components/platoon.vue'
  const { foldValidate } = useFormFold([])
  import useToast from '@/hooks/useToast'
  const dict = usePageDict('shortOrderDict')
  provide('dict', dict)

  const form = ref({})
  const otherParams = ref({})
  const formRef = ref({})
  const orderInfo = ref({})
  const orderId = ref()
  const workId = ref()
  const outCarMileage = ref()
  const outCarOil = ref()
  const defaultStaffId = ref()
  const defaultStaffName = ref()
  onLoad((options) => {
    orderId.value = options.id
    workId.value = options.workId
    form.value = {
      id: orderId.value,
      replaceTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      carSource: 1,
    }
    otherParams.value = JSON.parse(options.otherParam)
    form.value.replaceTime = otherParams.value.expectEndTime
    form.value.replaceStaffId = otherParams.value.replaceStaffId //工单负责人id
    form.value.replaceStaffName = otherParams.value.replaceStaffName //工单负责人name

    // 车辆(换上)
    form.value.carSource = otherParams.value.carSource
    form.value.carId = otherParams.value.carId
    form.value.carLicenseNo = otherParams.value.carLicenseNo
    form.value.carModelId = otherParams.value.carModelId
    form.value.carModelName = otherParams.value.carModelName
    // 初始化 获取订单详情
    getShortOrdrDetailsAPI({ id: orderId.value }).then((res) => {
      const result = res.result
      orderInfo.value = result.orderInfo

      form.value.orderCarId = orderInfo.value.useOrderCarId
      // form.value.carId = orderInfo.value.carId
      form.value.siteId = orderInfo.value.siteId
      form.value.siteName = orderInfo.value.siteName
      form.value.originalModelId = orderInfo.value.originalModelId
      form.value.originalModelName = orderInfo.value.originalModelName
      form.value.startTime = orderInfo.value.startTime
      form.value.endTime = orderInfo.value.endTime
      form.value.rentDays = orderInfo.value.rentDays
      form.value.orderSourceName = orderInfo.value.orderSourceName
      // 出库里程、出库油电量取值修改
      if (Array.isArray(orderInfo.value.shortOrderCarInfoDtos)) {
        let carInfoDtos = orderInfo.value.shortOrderCarInfoDtos.slice(-1)[0]
        outCarMileage.value = carInfoDtos ? carInfoDtos.startCarMileage : 0 // 出库里程
        outCarOil.value = carInfoDtos ? carInfoDtos.startCarOil : 0 // 出库油电量
      }
      // 车务专员 | 当前登录者 id
      handleDefaultStaff()
    })
  })

  // 处理员工默认值
  const handleDefaultStaff = () => {
    getUserInfo().then(({ employeeId, employeeName }) => {
      defaultStaffId.value = employeeId
      defaultStaffName.value = employeeName
      // 默认交车人
      form.value.replaceStaffId = defaultStaffId.value
      form.value.replaceStaffIdName = defaultStaffName.value
    })
  }
  // 最后一次交车信息
  const lastOrderCarInfo = computed(() => {
    const orderCarInfos = orderInfo.value.shortOrderCarInfoDtos
    let lastOrderCarInfo = {}
    if (orderCarInfos && orderCarInfos.length > 0) {
      lastOrderCarInfo = orderCarInfos[orderCarInfos.length - 1]
    }
    return lastOrderCarInfo
  })

  const stepList = ['换下车信息', '换上车信息', '换车费信息']
  const activeStepListIndex = ref(0)

  const rules = computed(() => {
    let changeRules = {}
    if (activeStepListIndex.value == 0) {
      changeRules.endCarMileage = { required: true, message: '请输入换下车里程' }
      changeRules.endCarOil = { required: true, message: '请输入换下车油(电)量' }
    }
    if (activeStepListIndex.value == 1) {
      changeRules.startCarMileage = { required: true, message: '请输入换上车里程' }
      changeRules.startCarOil = { required: true, message: '请输入换上车油(电)量' }
      changeRules.carLicenseNo = { required: true, message: '请选择车牌号' }
    }
    return changeRules
  })

  provide('form', form)

  // 顶部统计信息
  const summaryLease = computed(() => {
    const orderInfoVal = orderInfo.value
    return [
      { label: '预计租赁周期', slotName: 'leasePeriod' },
      { label: '交车车牌号', value: orderInfoVal.carLicenseNo },
      { label: '订单获取方式', value: orderInfoVal.orderAcquisitionTypeName },
      { label: '预订车型', value: orderInfoVal.originalSiteModelName },
      { label: '交车车型', value: orderInfoVal.carModelName },
      { label: '订单来源', value: orderInfoVal.orderSourceName },
    ]
  })

  const priceTemplateId = ref()
  const feeFormRef = ref()
  const feeForm = ref({
    randomKey: 0,
    orderFee: [
      {
        // 费用类型（线上费用|线下费用）
        feeType: 1,
        feeDetailList: [],
        priceTemplateId: priceTemplateId,
        feeDetailTypeList: ['extraFee'],
      },
    ],
  })
  provide('feeForm', feeForm)

  // 点击下一步
  let isInitFeeDetail = false
  const stepClickFn = (operate) => {
    // 当前 step
    let currStep = activeStepListIndex.value
    let nextStep = operate == 'next' ? currStep + 1 : currStep - 1
    if ((currStep == 0 || currStep == 1) && operate == 'next') {
      formRef.value.validate((valid, errors) => {
        if (valid) {
          activeStepListIndex.value = nextStep
          scrollToTopFn()
          // 读取费用配置
          // 读取门店模板配置
          if (!isInitFeeDetail) {
            isInitFeeDetail = true
            getStoreTemplateDetail(orderInfo.value.siteId, 1, (storeTemplate, templateId) => {
              // 初始化费用
              initFeeDetail(feeForm.value, storeTemplate)
              // 更新费用模板 id
              priceTemplateId.value = templateId
            })
          }
        } else {
          foldValidate(errors, true)
        }
      })
    } else {
      activeStepListIndex.value = nextStep
      scrollToTopFn()
    }
  }
  // 滚动到页面顶部
  const scrollToTopFn = () => {
    uni.pageScrollTo({
      scrollTop: 0,
      duration: 200,
    })
  }
  // 确认换车
  const okLoading = ref(false)
  const submitOperateFn = () => {
    let feeFormValue = feeForm.value
    let costInfo = buildCostInfoParam(feeFormValue)
    const param = {
      ...form.value,
      orderFee: costInfo.orderFee[0],
    }
    param.id = workId.value
    okLoading.value = true
    finishReplaceCarAPI(param)
      .then((res) => {
        useToast({
          title: res.result?.msg || res.message || '操作成功',
          icon: 'none',
        }).then(() => {
          uni.$emit('operateSuccess', 'change-car')
          uni.navigateBack({
            delta: 1,
          })
        })
      })
      .catch(() => {
        okLoading.value = false
      })
  }
  // 检验换下车车辆是否存在与当前订单关联的状态为已开始的ETC订单
  const etcModalRef = ref()
  const submitFn = () => {
    let params = {
      refType: 1,
      refId: orderId.value,
      carId: orderInfo.value.carId,
      endTime: form.value.replaceTime,
    }
    checkExistEtcOrderApi(params).then((res) => {
      let result = res.result
      if (result.existOrder) {
        let params = {
          carLicenseNo: orderInfo.value.carLicenseNo,
          operateStr: '换车',
        }
        etcModalRef.value.open(params)
      } else {
        submitOperateFn()
      }
    })
  }
</script>
<style lang="less" scoped>
  .container {
    display: flex;
    flex-direction: column;
    .step-wrap {
      border-top: 2rpx solid #f7f8fa;
      background-color: #ffffff;
      position: fixed;
      top: var(--window-top);
      left: 0;
      width: 100%;
      z-index: 1000;
    }
    .order-change-content {
      padding: 24rpx;
      padding-top: 178rpx;
    }
    #footer-box {
      position: fixed;
      bottom: 0;
      background-color: #ffffff;
      z-index: 100;
      /deep/ .ve-button {
        padding: 0;
      }
    }
  }
  .lease-period-rentdays {
    font-size: 30rpx;
    color: #3072f6;
    margin-top: 8rpx;
  }
  .rent-days {
    font-size: 30rpx;
    text-align: right;
    color: #3072f6;
  }

  .fee-pane-content {
    /deep/ .ve-card-content {
      padding-bottom: 0;
    }
  }
  .platoon-wrapper {
    /deep/ .form-item-type {
      .ve-form-item__border {
        display: none;
      }
    }
    /deep/ .ve-card {
      box-shadow: none;
    }
    /deep/.ve-card-header {
      display: none;
    }
    /deep/ .ve-card-content {
      padding: 0;
    }
    /deep/ .ve-card-header-border-line {
      display: none;
    }
    .edit-lease-return-border {
      margin-top: 10rpx;
      height: 2rpx;
      width: 100%;
      background: rgba(216, 216, 216, 0.3);
    }
  }
</style>
